package br.com.keropizza.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import br.com.keropizza.dominio.Cliente;

@Repository
public class ClienteDao {

	@PersistenceContext
	private EntityManager entityManager;
	
	public Cliente buscaPorTelefone(String telefone) {
		Query query = entityManager.createQuery("select c from cliente as c where c.telefone = :telefone");
		query.setParameter("telefone", telefone);
		List<Cliente> resultList = query.getResultList();
		if(resultList.isEmpty()){
			return null;
		}
		return resultList.get(0);
	}

	public void adiciona(Cliente cliente) {
		entityManager.persist(cliente);
	}
	
	public List<Cliente> buscaTodosClientes(){
		Query query = entityManager.createQuery("select c from cliente as c");
		return query.getResultList();
	}
	
	public void altera(Cliente cliente){
		entityManager.merge(cliente);
	}
	
	public void remove(Cliente cliente){
		entityManager.remove(entityManager.getReference(Cliente.class, cliente.getId()));
	}
	
	public Cliente buscaPorId(Long id){
		return entityManager.find(Cliente.class, id);
	}
}
